using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using UnityEngine;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

public class UDPRecive : MonoBehaviour
{
    // Start is called before the first frame update
    private UdpClient udpClient = null;
    string locateIP = "127.0.0.1";
    int locatePort = 9002;
    void Start()
    {
        ReciveStart();
    }
  

    private void ReciveStart()
    {
       
        IPAddress locateIpAddr = IPAddress.Parse(locateIP);
        IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort);
        udpClient = new UdpClient(locatePoint);

        IPEndPoint remotePoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 9001);

        Task.Run(() =>
        {
            while (true)
            {
                if (udpClient != null)
                {
                    var received = udpClient.Receive(ref remotePoint);
                    string info = Encoding.UTF8.GetString(received);
                    string from =$"{ remotePoint.Address}:{ remotePoint.Port}";
                    Debug.Log(info);
                }
            }
        });
    }
    void OnApplicationQuit()
    {
        if (udpClient != null)
            udpClient.Close();  
    }
}
